package com.example.tacocloud;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.validation.Valid;

import com.example.tacocloud.Ingredient.Type;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
@RequestMapping("/design")
public class DesignTacoController {

    @Autowired
    private IngredientRepository ingredientRepo;

    private List<Ingredient> filterByType(List<Ingredient> ingredients, Type type) {
        List<Ingredient> filtered = new ArrayList<Ingredient>();
        for (var ingredient : ingredients) {
            if (ingredient.getType().equals(type)) {
                filtered.add(ingredient);
            }
        }
        return filtered;
    }
    
    @GetMapping
    public String showDesignForm(Model model) {
        var ingredients = new ArrayList<Ingredient>();
        ingredientRepo.findAll().forEach(i -> ingredients.add(i));

        Type[] types = Ingredient.Type.values();
        for (Type type : types) {
            model.addAttribute(type.toString().toLowerCase(), filterByType(ingredients, type));
        }

        model.addAttribute("design", new Taco());

        return "design";
    }

    @PostMapping
    public String submitDesignForm(@Valid Taco design, Errors errors) {
        if (errors.hasErrors()) {
            return "design";
        }

        // Save taco design
        log.info("Processing design: " + design);
        

        return "redirect:/orders/current";
    }
}
